package main

import "web/database"

// 查询单条数据示例
func queryRowDemo(n int, m int) (u goLib, err error) {
	u = goLib{}

	sqlStr := "select id, name, age from goLib where id=? and age=?"

	// 非常重要：确保QueryRow之后调用Scan方法，否则持有的数据库链接不会被释放
	err = database.Db.QueryRow(sqlStr, n, m).Scan(&u.id, &u.name, &u.age)

	return
}

// 查询多条数据示例
func queryMultiRowDemo() (users []goLib, err error) {
	sqlStr := "select id, name, age from goLib"
	rows, err := database.Db.Query(sqlStr)

	// 循环读取结果集中的数据
	for rows.Next() {
		u := goLib{}
		err = rows.Scan(&u.id, &u.name, &u.age)
		users = append(users, u)
	}

	// 非常重要：关闭rows释放持有的数据库链接
	defer rows.Close()

	return
}

func (a *goLib) Update() (err error) {
	sqlStr := "update goLib set age=?,name=? where id=?"
	_, err = database.Db.Exec(sqlStr, a.age, a.name, a.id)
	return
}

func (a *goLib) Insert() (err error) {
	sqlStr := "insert into goLib(age,name) values(?,?)"
	_, err = database.Db.Exec(sqlStr, a.age, a.name)
	return
}

// 预处理查询示例
func prepareQueryDemo(n int) (users []goLib, err error) {

	sqlStr := "select id, name, age from goLib where id > ?"
	stmt, err := database.Db.Prepare(sqlStr)

	rows, err := stmt.Query(n)

	// 循环读取结果集中的数据
	for rows.Next() {
		var u = goLib{}
		err = rows.Scan(&u.id, &u.name, &u.age)
		users = append(users, u)
	}
	defer stmt.Close()
	defer rows.Close()

	return
}

// 预处理插入示例
func (a *goLib) prepareInsertDemo() (err error) {
	sqlStr := "insert into goLib(age,name) values(?,?)"
	stmt, err := database.Db.Prepare(sqlStr)

	_, err = stmt.Exec(a.age, a.name)
	defer stmt.Close()

	return
}

// 预处理update示例
func (a *goLib) prepareUpdateDemo() (err error) {
	sqlStr := "update goLib set age=?,name=? where id=?"
	stmt, err := database.Db.Prepare(sqlStr)

	_, err = stmt.Exec(a.age, a.name, a.id)
	defer stmt.Close()

	return
}
